<template>
    <div class="container">
      <!-- 头部 -->
      <div class="header">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">角色管理系统</h1>
            <div class="divider"></div>
            <span class="subtitle">Total: {{ totalItems }}</span>
          </div>
          <div class="action-group">
            <el-input
              v-model="searchKeyword"
              placeholder="输入角色名称/标识"
              clearable
              @input="handleSearch"
              class="search-input"
              size="large"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" size="large" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新增角色
            </el-button>
          </div>
        </div>
      </div>
  
      <!-- 表格内容 -->
      <div class="table-container">
        <el-table
          :data="pageData"
          style="width: 100%"
          size="medium"
          stripe
          :cell-style="{ padding: '8px 12px' }"
          :header-cell-style="{ background: '#f8fafc', padding: '8px 12px', position: 'sticky', top: 0, zIndex: 1 }"
        >
         <el-table-column prop="roleId" label="角色ID" min-width="220" />
          <el-table-column prop="roleName" label="角色名称" min-width="220" />
          <el-table-column prop="roleKey" label="角色标识" min-width="220" />
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button link type="primary" @click="editRole(row)">编辑</el-button>
                <el-divider direction="vertical" />
                <el-button link type="info" @click="assignPermissions(row)">
                  分配权限
                </el-button>
                <el-divider direction="vertical" />
                <el-button link type="danger" @click="deleteRole(row.roleId)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 分页器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
  
      <!-- 编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditMode? '编辑角色' : '新增角色'"
        width="600px"
        destroy-on-close
        class="custom-dialog"
      >
        <el-form :model="formData" label-width="100px" label-position="left">
          <el-form-item label="角色名称" required>
            <el-input v-model="formData.roleName" />
          </el-form-item>
          <el-form-item label="角色标识" required>
            <el-input v-model="formData.roleKey" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Search, Plus } from '@element-plus/icons-vue';
  import {
    getRoles,
    createRole,
    updateRole,
    deleteRole as deleteRoleApi,
  } from '@/api/roleApi';
  import { useRouter } from 'vue-router';
  
  const router = useRouter();
  
  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(20);
  const totalItems = ref(0);
  const pageData = ref([]);
  const allData = ref([]); // 存储所有数据
  const searchKeyword = ref(''); // 搜索关键词
  
  // 对话框数据
  const dialogVisible = ref(false);
  const isEditMode = ref(false);
  const formData = ref({});
  
  // 防抖搜索
  let searchTimer = null;
  const handleSearch = () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
      currentPage.value = 1;
      filterData();
    }, 300);
  };
  
  // 加载数据
  const loadRoles = async () => {
    try {
      const params = {
        page: currentPage.value,
        size: pageSize.value,
        search: searchKeyword.value,
      };
      const res = await getRoles(params);
      allData.value = res.data.content || [];
      filterData();
      totalItems.value = res.data.total || 0;
    } catch (error) {
      ElMessage.error('数据加载失败');
      console.error(error);
    }
  };
  
  // 过滤数据
  const filterData = () => {
    if (searchKeyword.value === '') {
      pageData.value = allData.value;
    } else {
      pageData.value = allData.value.filter((item) => {
        return (
          item.roleName.includes(searchKeyword.value) ||
          item.roleKey.includes(searchKeyword.value)
        );
      });
    }
  };
  
  // 分页处理
  const handlePageChange = () => loadRoles();
  const handleSizeChange = () => {
    currentPage.value = 1;
    loadRoles();
  };
  
  // 打开对话框
  const handleCreate = () => {
    isEditMode.value = false;
    formData.value = {};
    dialogVisible.value = true;
  };
  
  const editRole = (row) => {
    isEditMode.value = true;
    formData.value = { ...row };
    dialogVisible.value = true;
  };
  
  // 提交表单
  const submitForm = async () => {
    try {
      const api = isEditMode.value? updateRole : createRole;
      await api(formData.value);
      ElMessage.success(isEditMode.value? '修改成功' : '创建成功');
      dialogVisible.value = false;
      loadRoles();
    } catch (error) {
      ElMessage.error('操作失败');
      console.error(error);
    }
  };
  
  // 删除确认
  const deleteRole = async (id) => {
    try {
      await ElMessageBox.confirm('此操作将永久删除该角色，是否继续？', '警告', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        cancelButtonClass: 'el-button--text',
      });
      await deleteRoleApi(id);
      ElMessage.success('删除成功');
      loadRoles();
    } catch (error) {
      if (error!== 'cancel') {
        ElMessage.error('删除失败');
      }
    }
  };

  
  
  // 新增分配权限方法
  const assignPermissions = (role) => {
  if (!role.roleId) { // 根据实际字段名调整
    ElMessage.error('角色ID无效，无法分配权限')
    return
  }
  router.push({
    name: 'role-permission-assignment',
    params: { roleId: role.roleId }
  })
}
  
  // 初始化加载
  onMounted(loadRoles);
  </script>
  
  <style scoped>
  .container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #ffffff;
  }
  
  .header {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    padding: 10px 10px;
    border-bottom: 1px solid #e2e8f0;
    flex-shrink: 0;
  }
  
  .header-content {
    max-width: 1440px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 5px;
  }
  
  .title-section {
    display: flex;
    align-items: center;
    gap: 24px;
  }
  
  .page-title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    letter-spacing: 0.5px;
  }
  
  .subtitle {
    color: #64748b;
    font-size: 14px;
  }
  
  .divider {
    width: 2px;
    height: 24px;
    background: #cbd5e1;
  }
  
  .action-group {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .search-input {
    width: 320px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  
  .table-container {
    flex: 1;
    padding: 5px 0px;
    overflow-y: auto;
    background: #ffffff;
  }
  
  :deep(.el-table) {
    --el-table-border-color: #e2e8f0;
    --el-table-header-bg-color: #f8fafc;
    --el-table-row-hover-bg-color: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
  }
  
  :deep(.el-table th) {
    font-weight: 600;
    color: #475569;
  }
  
  :deep(.el-table td) {
    color: #475569;
  }
  
  .pagination-wrapper {
    padding: 16px 32px;
    background: rgba(255, 255, 255, 0.9);
    border-top: 1px solid #e2e8f0;
    flex-shrink: 0;
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  :deep(.custom-dialog) {
    border-radius: 12px;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
  }
  
  :deep(.custom-dialog .el-dialog__header) {
    padding: 24px;
    border-bottom: 1px solid #e2e8f0;
    margin-right: 0;
  }
  
  :deep(.custom-dialog .el-dialog__body) {
    padding: 24px;
  }
  
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  ::-webkit-scrollbar-thumb {
    background-color: #cbd5e1;
    border-radius: 8px;
    border: 2px solid transparent;
    background-clip: content-box;
  }
  
  ::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 8px;
  }
  </style>